package shujia.day15;

import java.util.concurrent.locks.ReentrantLock;

/*
    死锁：线程之间存在相互等待的现象

    中国人和外国人用餐案例：
    前提：中国人吃饭必须拥有两支筷子【锁A】，外国人吃饭必须有一把刀和一把叉【锁B】
    现在：中国人（一支筷子，一把刀） 外国人（一支筷子，一把叉）


 */
class Locks{
    public static final ReentrantLock LOCK_1 = new ReentrantLock();
    public static final ReentrantLock LOCK_2 = new ReentrantLock();
}

class MyThread7 extends Thread{
    boolean flag;

    public MyThread7(boolean flag) {
        this.flag = flag;
    }

    @Override
    public void run() {
        if(flag){
            synchronized (Locks.LOCK_1){
                System.out.println("if lock1");
                synchronized (Locks.LOCK_2){
                    System.out.println("if lock2");
                }
            }
        }else {
            synchronized (Locks.LOCK_2){
                System.out.println("else lock2");
                synchronized (Locks.LOCK_1){
                    System.out.println("else lock1");
                }
            }
        }
    }
}

public class DieLockDemo {
    public static void main(String[] args) {
        MyThread7 t1 = new MyThread7(true);
        MyThread7 t2 = new MyThread7(false);

        t1.start();
        t2.start();

    }
}
